/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

namespace DNNContentBuilder.UserControls
{
	using System;
	using System.Collections;
	using System.Data;
	using System.Data.OleDb;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for ConnectionStringControl.
	/// </summary>
	public class DataConnectionControl : System.Web.UI.UserControl
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/DataConnectionControl";

		protected System.Web.UI.WebControls.LinkButton			btNewConn;
		protected System.Web.UI.WebControls.LinkButton			btUpdate;
		protected System.Web.UI.WebControls.LinkButton			btDelete;
		protected System.Web.UI.WebControls.LinkButton			btCancel;
		protected System.Web.UI.WebControls.RadioButtonList		RadioButtonList1;
		protected System.Web.UI.WebControls.LinkButton			btSearchConn;
		protected System.Web.UI.WebControls.Literal             ltErrorMessage;

		private   ConnectionStringInfo csInfo = new ConnectionStringInfo();
		private   DataConnectionInfo dcInfo = new DataConnectionInfo();
		private	  DatabaseInfo dbInfo = new DatabaseInfo();

		protected System.Web.UI.WebControls.Label				msgTestConn;
		protected System.Web.UI.WebControls.DropDownList		ddString;
		protected System.Web.UI.WebControls.DropDownList		ddPK;
		protected System.Web.UI.WebControls.DropDownList		ddTables;
		protected System.Web.UI.HtmlControls.HtmlInputHidden	txtDataId;
		protected System.Web.UI.WebControls.DataList			DataConnList;
		protected System.Web.UI.WebControls.Panel				DataConnFormPanel;
		protected System.Web.UI.WebControls.Panel				DataConnListPanel;

		private   DataConnectionController dcController = new DataConnectionController();
		private   ConnectionStringController csController = new ConnectionStringController();
		private   DatabaseController dbController = new DatabaseController();
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here

			if (IsPostBack) 
			{
				this.btDelete.Attributes.Add("onClick", "javascript:return confirm('" + Commons.GetLocalizedString("label_ConfirmDelete", resource) + "')");
			}

			this.btUpdate.Text		= Commons.GetLocalizedString("button_Update", resource);
			this.btDelete.Text		= Commons.GetLocalizedString("button_Delete", resource);
			this.btCancel.Text		= Commons.GetLocalizedString("button_Cancel", resource);
			this.btNewConn.Text		= Commons.GetLocalizedString("button_Create", resource);
			this.btSearchConn.Text	= Commons.GetLocalizedString("button_Search", resource);

			this.FillList();
			
			ltErrorMessage.Text = "";
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			this.FillddString();
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btSearchConn.Click += new System.EventHandler(this.btSearchConn_Click);
			this.btUpdate.Click += new System.EventHandler(this.btUpdate_Click);
			this.btDelete.Click += new System.EventHandler(this.btDelete_Click);
			this.btCancel.Click += new System.EventHandler(this.btSearchConn_Click);
			this.DataConnList.ItemCreated += new System.Web.UI.WebControls.DataListItemEventHandler(this.DataConnList_ItemCreated);
			this.btNewConn.Click += new System.EventHandler(this.btNewConn_Click);
			this.Load += new System.EventHandler(this.Page_Load);

			this.ddTables.SelectedIndexChanged += new System.EventHandler(this.ddTables_SelectedIndexChanged);
			this.ddString.SelectedIndexChanged += new System.EventHandler(this.ddString_SelectedIndexChanged);

		}
		#endregion

		private bool FillddString()
		{
			int index = ddString.SelectedIndex;
			
			this.ddString.DataSource = (ICollection)csController.GetAllConnections();
			this.ddString.DataTextField = "Title";
			this.ddString.DataValueField = "ConnectionStringId";
			this.ddString.DataBind();

			if (index > ddString.Items.Count) {
				index = 0;	
			}
			
			ddString.SelectedIndex = index;

			if (ddString.Items.Count == 0) 
			{ 
				return false;
			}

			return true;
		}

		private void FillddTables(Int32 connectionStringId) 
		{
			csInfo = (ConnectionStringInfo)csController.GetItem(connectionStringId);
			dbInfo = (DatabaseInfo)dbController.GetItem(csInfo.DatabaseId);

			OleDbConnection tableSourceConnection = new OleDbConnection(csInfo.ConnectionString);

			OleDbCommand tableSourceCommand = new OleDbCommand(dbInfo.SysTableQuery, tableSourceConnection);

			try 
			{
				tableSourceConnection.Open();

				OleDbDataReader tableSourceReader = tableSourceCommand.ExecuteReader(CommandBehavior.CloseConnection);
				// table_name is the default name in both Oracle and SQL Server, so will be default for everyone
				this.ddTables.DataSource = tableSourceReader;
				this.ddTables.DataTextField = "table_name";
				this.ddTables.DataValueField = "table_name";
				this.ddTables.DataBind();

				ddTables.SelectedIndex = 0;

			}
			catch (Exception)
			{
				return;
			}

		}

		private void FillddPK (Int32 connectionStringId, string tableName) 
		{
			csInfo = (ConnectionStringInfo)csController.GetItem(connectionStringId);
			dbInfo = (DatabaseInfo)dbController.GetItem(csInfo.DatabaseId);

			OleDbConnection tableSourceConnection = new OleDbConnection(csInfo.ConnectionString);

			OleDbCommand tableSourceCommand = new OleDbCommand(dbInfo.SysColumnQuery.Replace("@table_name", tableName), tableSourceConnection);

			try 
			{
				tableSourceConnection.Open();
				OleDbDataReader tableSourceReader = tableSourceCommand.ExecuteReader(CommandBehavior.CloseConnection);
				this.ddPK.DataSource = tableSourceReader;
				this.ddPK.DataTextField = "name" ;
				this.ddPK.DataValueField = "name";
				this.ddPK.DataBind();
			}
			catch (Exception) 
			{
				return;
			}
		}

		private void FillList() 
		{
			this.DataConnList.DataSource = (ICollection)dcController.GetAllDataConnections();
			this.DataConnList.DataBind();
			
			btDelete.Visible = false;
			
			FillDropDowns();
		}

		
		private void btSearchConn_Click(object sender, System.EventArgs e)
		{
			ClearFields();
		}

		private void btNewConn_Click(object sender, System.EventArgs e)
		{
			if (!this.FillddString()) 
			{
				return;
			}
			
			if(!FillDropDowns()) {
				return;
			}
			
			this.DataConnListPanel.Visible = false;
			this.DataConnFormPanel.Visible = true;
		}
		
		private bool FillDropDowns() {
			if (!this.FillddString()) 
			{
				return false;
			}
			
			int index = ddTables.SelectedIndex;
			
			this.FillddTables(Int32.Parse(this.ddString.SelectedValue));

			this.ddTables.SelectedIndex = index;
			
			index = ddPK.SelectedIndex;

			this.FillddPK(Int32.Parse(this.ddString.SelectedValue), ddTables.SelectedValue);

			this.ddPK.SelectedIndex = index;
			
			return true;
		}

		private void btUpdate_Click(object sender, System.EventArgs e)
		{
			dcInfo.ConnectionStringId = Int32.Parse(this.ddString.SelectedValue);
			dcInfo.TableName = this.ddTables.SelectedValue;
			dcInfo.PrimaryKeyName = this.ddPK.SelectedValue;

			if (this.txtDataId.Value == "") 
			{
				dcController.Add(dcInfo);
			} 
			else 
			{
				dcInfo.DataConnectionId = Int32.Parse(txtDataId.Value);
				try 
				{
					dcController.Update(dcInfo);
				} 
				catch (Exception error)
				{
                   string msg = error.Message;
				}
			}
			
			ClearFields();
		}

		private void ShowError(string message, string error) {
			ltErrorMessage.Visible = true;
			ltErrorMessage.Text = @"
			<script language='javascript'>
			<!-- 
			    alert('{0}') 
			-->
			</script>
			";
			ltErrorMessage.Text = String.Format(ltErrorMessage.Text, message).Replace("\r","").Replace("\n","");
			ltErrorMessage.Text = ltErrorMessage.Text.Replace("<!--","\n<!--\n").Replace("-->","\n-->\n");
		}

		private void btDelete_Click(object sender, System.EventArgs e)
		{
			if (txtDataId.Value != "") 
			{
				try {
					dcController.Delete(Int32.Parse(txtDataId.Value));
				}
				catch (Exception ) {
					ShowError(Commons.GetLocalizedString("label_CannotDeleteDueDependencies", resource), "");
				}
			}
			
			ClearFields();
		}

		private void btCancel_Click(object sender, System.EventArgs e)
		{
			ClearFields();
		}

		private void btDataConnSelected_OnClick(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			ImageButton btDataConnSelected = (ImageButton)sender;
			dcInfo = (DataConnectionInfo)dcController.GetItem(Int32.Parse(btDataConnSelected.CommandArgument));

			this.DataConnListPanel.Visible = false;
			this.DataConnFormPanel.Visible = true;

			this.FillddString();
			this.ddString.SelectedValue = dcInfo.ConnectionStringId.ToString();

			this.FillddTables(dcInfo.ConnectionStringId);
			this.ddTables.SelectedValue = dcInfo.TableName;

			this.FillddPK(dcInfo.ConnectionStringId, dcInfo.TableName);
			this.ddPK.SelectedValue = dcInfo.PrimaryKeyName;

			btDelete.Visible = true;
			
			this.ddString.Enabled = false;
			this.ddTables.Enabled = false;
			

			this.txtDataId.Value = dcInfo.DataConnectionId.ToString();
		}


		private void ClearFields () {
			this.ddString.SelectedIndex = 0;

			this.FillddTables(Int32.Parse(this.ddString.SelectedValue));

			this.ddTables.SelectedIndex = 0;

			this.FillddPK(Int32.Parse(this.ddString.SelectedValue), ddTables.SelectedValue);

			this.ddPK.SelectedIndex = 0;

			txtDataId.Value = "";
            
			this.DataConnListPanel.Visible = true;
			this.DataConnFormPanel.Visible = false;

			this.ddString.Enabled = true;
			this.ddTables.Enabled = true;

			this.btDelete.Visible = false;

			FillList();
		}


		private void DataConnList_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e) 
		{ 
			ListItemType elemType = e.Item.ItemType;

			if ((elemType == ListItemType.Item) || (elemType == ListItemType.AlternatingItem))
			{ 
				ImageButton imgButton = (ImageButton) e.Item.FindControl("btDataConnSelected"); 
				imgButton.Click += new System.Web.UI.ImageClickEventHandler(btDataConnSelected_OnClick); 
			}  
		}


		private void ddTables_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			this.FillddPK(Int32.Parse(ddString.SelectedValue), ddTables.SelectedValue);
		} 

		private void ddString_SelectedIndexChanged(object sender, System.EventArgs e)
		{

			this.FillddTables(Int32.Parse(ddString.SelectedValue));

			ddTables.SelectedIndex = 0;

			this.FillddPK(Int32.Parse(ddString.SelectedValue), ddTables.SelectedValue);
		} 
	}
}
